#!/usr/bin/env python
'''
Created on 2011-5-18

@author: elm
'''


# -----------------------------------------------------------------------------
# calc.py
#
# A simple calculator with variables.   This is from O'Reilly's
# "Lex and Yacc", p. 63.
#
# Class-based example contributed to PLY by David McNab
# -----------------------------------------------------------------------------

import sys
sys.path.insert(0,"../..")

if sys.version_info[0] >= 3:
    raw_input = input

from ddbms.SqlParser import SqlBaseParser

class SqlFormatter(SqlBaseParser):
    
    def ops(self,op):
        return op.upper()
    
    def statement(self,fieldrefs,tablerefs,where):
        'parse a sql statement'
        if(where==None):
            return 'SELECT  '+fieldrefs+'\nFROM    '+tablerefs
        else:
            return 'SELECT  '+fieldrefs+'\nFROM    '+tablerefs+'\nWHERE   '+where
    
    def tablerefs(self,refs):
        'parse "from" clause'
        str=''     
        first = True
        for ref in refs:
            if(first):
                first=False
            else:
                str+=', '           
            str+=ref
        str+=''            
        return str;
    
    def tableref(self,table):
        'parse a table reference in "from" clause'
        return '['+table+']'
    
    def fieldrefs_all(self):  
        'parse star(*) in "select" clause'      
        return '*'
    
    def fieldrefs(self,refs):
        'parse referred fields in "select" clause'
        str=''     
        first = True
        for ref in refs:
            if(first):
                first=False
            else:
                str+=', '           
            str+=ref
        str+=''            
        return str;
        
    def fieldref(self,table,col):
        'parse a field reference'
        if(table==None):
            return "_default.["+col+']'
        else:
            return table+'.['+col+']'        
    
    def condition_operation_binary(self,left,op,right):
        'binary operators (and, or)'
        return '('+left + ' ' + op + ' ' + right+')'
    
    def condition_operation_self(self,op,right):
        'unary operations (not)'
        return '('+ op + ' ' + right+')'
    
    def condition_value(self,fieldref,op,value):
        '''parse a condition clause 
           which compares a field and a value, i.e. x>1'''
        return fieldref + ' ' + op+' ' + str(value)
        
    def condition_field(self,leftfield,op,rightfield):
        '''parse a condition clause 
           which compares two fields, i.e. x>y'''
        return leftfield + ' ' + op + ' ' + rightfield
    
    def value_number(self,v):
        'parse a number'  
        if(v.find('.')<0):
            return int(v)
        else:
            return float(v)
    
    def value_string(self,v):
        return str(v)
    